package com.smsclient.config;


import com.smsclient.handler.CMPPSessionConnectedHandler;
import com.smsclient.model.IspType;
import com.zx.sms.connect.manager.EndpointEntity;
import com.zx.sms.connect.manager.EndpointManager;
import com.zx.sms.connect.manager.cmpp.CMPPClientEndpointEntity;
import com.zx.sms.handler.api.BusinessHandlerInterface;
import io.netty.util.ResourceLeakDetector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class ClientConnConfig {

    @Value(value = "${cmppconfig.smsserve.host}")
    private String host;
    @Value(value = "${cmppconfig.smsserve.port}")
    private Integer port;
    @Value(value = "${cmppconfig.smsserve.accout}")
    private String accout;
    @Value(value = "${cmppconfig.smsserve.password}")
    private String password;
    @Value(value = "${cmppconfig.smsserve.version}")
    private String version;
    @Value(value = "${cmppconfig.smsserve.maxChannels}")
    private short maxChannels;

    @Bean("CMPPClientEndpointEntity")
    public CMPPClientEndpointEntity getCMPPClientEndpointEntity(){
        CMPPClientEndpointEntity client = new CMPPClientEndpointEntity();
        client.setId("client");
        client.setHost(host);
        client.setPort(port);
        client.setChartset(Charset.forName("utf-8"));
        client.setGroupName(IspType.CM.getIspCode());
        client.setUserName(accout);
        client.setPassword(password);
        log.info(version);
        client.setMaxChannels(maxChannels);
        client.setVersion((short)0x20);
        client.setRetryWaitTimeSec((short)30);
        client.setUseSSL(false);
        client.setReSendFailMsg(true);
        client.setSupportLongmsg(EndpointEntity.SupportLongMessage.BOTH);
        List<BusinessHandlerInterface> clienthandlers = new ArrayList<BusinessHandlerInterface>();
        clienthandlers.add( new CMPPSessionConnectedHandler(10000));
        client.setBusinessHandlerSet(clienthandlers);
        return client;
    }

    @Bean
    public void endpointManager(){
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
        final EndpointManager manager = EndpointManager.INS;
        manager.addEndpointEntity(getCMPPClientEndpointEntity());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //开启客户端
        manager.openEndpoint(getCMPPClientEndpointEntity());
//        Thread.sleep(5000);
        System.out.println("start.....");

//        LockSupport.park();
    }


}
